<template>
    <div class="price-config">
        <popup
            ref="popupRef"
            title="运价配置"
            :async="true"
            width="1000px"
            @confirm="handleSave"
            @close="handleClose"
        >
            <el-form :model="formData" class="mb-4">
                <el-form-item label="所属公司" required>
                    <el-select 
                        v-model="formData.company_id" 
                        placeholder="请选择公司"
                        :disabled="!isAdd"
                        class="w-[300px]"
                    >
                        <el-option
                            v-for="item in companyOptions"
                            :key="item.id"
                            :label="item.company_name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
            </el-form>

            <el-card class="mb-4">
                <template #header>
                    <div class="flex justify-between items-center">
                        <span>里程区间价格配置</span>
                        <el-button type="primary" @click="handleAddMileage">添加区间</el-button>
                    </div>
                </template>
                
                <el-table :data="mileageRules" border>
                    <el-table-column label="起始里程(km)" width="180" align="center">
                        <template #default="{ row, $index }">
                            <template v-if="$index === mileageRules.length - 1">
                                <span>{{ row.start }}</span>
                            </template>
                            <template v-else>
                                <el-input-number 
                                    v-model="row.start" 
                                    :min="0" 
                                    :precision="1"
                                    :disabled="$index > 0"
                                />
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="结束里程(km)" width="180" align="center">
                        <template #default="{ row, $index }">
                            <template v-if="$index === mileageRules.length - 1">
                                <span>无穷大</span>
                            </template>
                            <template v-else>
                                <el-input-number v-model="row.end" :min="0" :precision="1" />
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="计价类型" width="150" align="center">
                        <template #default="{ row }">
                            <el-select v-model="row.type">
                                <el-option label="固定计价" :value="1" />
                                <el-option label="动态计价" :value="2" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="价格" align="center">
                        <template #default="{ row }">
                            <div class="flex items-center justify-center gap-2">
                                <template v-if="row.type === 1">
                                    <span>固定价：</span>
                                    <el-input-number v-model="row.fixed_price" :min="0" :precision="2" />
                                    <span>元</span>
                                </template>
                                <template v-else>
                                    <span>每公里：</span>
                                    <el-input-number v-model="row.per_km_price" :min="0" :precision="2" />
                                    <span>元</span>
                                </template>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100" align="center">
                        <template #default="{ $index }">
                            <el-button 
                                v-if="$index !== 0 && $index !== mileageRules.length - 1"
                                type="danger" 
                                link 
                                @click="removeMileageRule($index)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>

            <el-card>
                <template #header>
                    <div class="flex justify-between items-center">
                        <span>时段加价配置</span>
                        <el-button type="primary" @click="handleAddTimeRule">添加规则</el-button>
                    </div>
                </template>
                
                <el-table :data="timeRules" border>
                    <el-table-column label="开始时间" width="180" align="center">
                        <template #default="{ row }">
                            <el-time-picker
                                style="width: 150px;"
                                v-model="row.start_time"
                                format="HH:mm"
                                placeholder="开始时间"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="结束时间" width="180" align="center">
                        <template #default="{ row }">
                            <el-time-picker
                                style="width: 150px;"
                                v-model="row.end_time"
                                format="HH:mm"
                                placeholder="结束时间"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="加价类型" width="150" align="center">
                        <template #default="{ row }">
                            <el-select v-model="row.type">
                                <el-option label="固定加价" :value="1" />
                                <el-option label="动态加价" :value="2" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="加价" align="center">
                        <template #default="{ row }">
                            <div class="flex items-center justify-center gap-2">
                                <template v-if="row.type === 1">
                                    <span>固定加价：</span>
                                    <el-input-number v-model="row.fixed_price" :min="0" :precision="2" />
                                    <span>元</span>
                                </template>
                                <template v-else>
                                    <span>每公里加价：</span>
                                    <el-input-number v-model="row.per_km_price" :min="0" :precision="2" />
                                    <span>元</span>
                                </template>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100" align="center">
                        <template #default="{ $index }">
                            <el-button type="danger" link @click="removeTimeRule($index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </popup>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import feedback from '@/utils/feedback'
import Popup from '@/components/popup/index.vue'
import { companyAllLists } from '@/api/supervise/company'
import { fareSave } from '@/api/supervise/fare'

const popupRef = shallowRef<InstanceType<typeof Popup>>()

const formData = ref({
    company_id: undefined,
})
const isAdd = ref(true)
// 公司列表
const companyOptions = ref<Array<{ id: number, company_name: string }>>([])

// 里程区间规则
const mileageRules = ref([
    {
        start: 0,
        end: 3,
        type: 1,
        fixed_price: 10,
        per_km_price: 0
    },
    {
        start: 3,
        end: Infinity,
        type: 2,
        fixed_price: 0,
        per_km_price: 1
    }
])

// 时段加价规则
const timeRules = ref([
    // {
    //     start_time: new Date(2000, 1, 1, 6, 0),
    //     end_time: new Date(2000, 1, 1, 8, 0),
    //     type: 2, // 1: 固定加价 2: 动态加价
    //     fixed_price: 0,
    //     per_km_price: 1
    // }
])

// 添加里程区间规则
const handleAddMileage = () => {
    const rulesLength = mileageRules.value.length
    if (rulesLength < 2) return
    
    // 获取倒数第二条规则
    const lastSecondRule = mileageRules.value[rulesLength - 2]
    // 获取最后一条规则（无穷大规则）
    const lastRule = mileageRules.value[rulesLength - 1]
    
    // 在倒数第二条和最后一条之间插入新规则
    mileageRules.value.splice(rulesLength - 1, 0, {
        start: lastSecondRule.end,
        end: lastSecondRule.end + 1,
        type: 2,
        fixed_price: 0,
        per_km_price: 1
    })
}

// 删除里程区间规则
const removeMileageRule = (index: number) => {
    // 不允许删除第一条和最后一条规则
    if (index === 0 || index === mileageRules.value.length - 1) return
    mileageRules.value.splice(index, 1)
}

// 添加时段规则
const handleAddTimeRule = () => {
    timeRules.value.push({
        start_time: new Date(2000, 1, 1, 0, 0),
        end_time: new Date(2000, 1, 1, 0, 0),
        type: 2,
        fixed_price: 0,
        per_km_price: 1
    })
}

// 删除时段规则
const removeTimeRule = (index: number) => {
    timeRules.value.splice(index, 1)
}

// 保存配置
const handleSave = async () => {
    if (!formData.value.company_id) {
        return feedback.msgError('请选择公司')
    }
    try {   
        const params = {
            company_id: formData.value.company_id,
            extend: {
                mileage_rules: mileageRules.value,
                time_rules: timeRules.value.map((rule:any) => ({
                    type: rule.type,
                    fixed_price: rule.fixed_price,
                    per_km_price: rule.per_km_price as number,
                    start_time: formatTime(rule.start_time),
                    end_time: formatTime(rule.end_time)
                }))
            },
        }
        // TODO: 调用保存接口
        await fareSave(params)
        feedback.msgSuccess('保存成功')
    } catch (error) {
        console.error(error)
    }
}

// 格式化时间
const formatTime = (date: Date) => {
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
}

// 添加 emit 定义
const emit = defineEmits(['success', 'close'])

// 添加关闭处理方法
const handleClose = () => {
    emit('close')
}

const getCompanyOptions = async () => {
    try {
        const res = await companyAllLists({})
        companyOptions.value = res
    } catch (error) {
        console.error(error)
    }
}

// 添加 show 方法
defineExpose({
    show: (data: any) => {
        // 判断是否为新增
        isAdd.value = !data.id
        // 新增时获取公司列表
        getCompanyOptions()

        if (isAdd.value) {
            // 重置表单数据
            formData.value.company_id = undefined
            // 重置数据到默认值，确保始终有两条规则
            mileageRules.value = [
                {
                    start: 0,
                    end: 3,
                    type: 1,
                    fixed_price: 10,
                    per_km_price: 0
                },
                {
                    start: 3,
                    end: Infinity,
                    type: 2,
                    fixed_price: 0,
                    per_km_price: 1
                }
            ]
            timeRules.value = []
        } else {
            // 编辑时设置公司ID
            formData.value.company_id = data.company_id
            mileageRules.value = data.extend.mileage_rules
            timeRules.value = data.extend.time_rules.map((rule:any) => ({
                start_time: new Date(`2000-01-01 ${rule.start_time}`),
                end_time: new Date(`2000-01-01 ${rule.end_time}`),
                type: rule.type,
                fixed_price: rule.fixed_price,
                per_km_price: rule.per_km_price
            }))
        }
        // 打开弹窗
        popupRef.value?.open()
    }
})

// 监听里程区间变化
watch(mileageRules, (newRules) => {
    if (newRules.length >= 2) {
        // 遍历规则（除最后一条），更新下一条规则的起始里程
        for (let i = 0; i < newRules.length - 1; i++) {
            const currentRule = newRules[i]
            const nextRule = newRules[i + 1]
            // 将下一条规则的起始里程设置为当前规则的结束里程
            nextRule.start = currentRule.end
        }
    }
}, { deep: true })
</script>

<style lang="scss" scoped>
.price-config {
    :deep(.el-dialog__body) {
        padding: 20px;
    }
}
</style>